package model

import (
	"fmt"
	"gowork/newCustomers/pool"
	"gowork/newCustomers/utils"
	"sync"
	"time"
)

type User struct {
	Id int64 `xorm:"pk autoincr"`
	Name string `xorm:"index"`
	InfoTypeList []*InfoType `xorm:"-"`
	//InfoTypeList []*InfoType
	Sex int
	Bmi float64
	InitialBodyWeight float64
	CurrentWeight float64
	TargetWeight float64
	LatestServiceStartTime time.Time
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Account struct {
	AccountId int64 `xorm:"pk autoincr"`
	DepartMentId int64
	DepartMentName string
	AccountName string
	Level int
	Incumbency int
	CreatedAt time.Time
	UpdatedAt time.Time
}

type NewCustomerDistribution struct {
	Id int64 `xorm:"pk autoincr"`
	UserName string
	UserId int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type DCustomerDistribution struct {
	Id int64 `xorm:"pk autoincr"`
	UserName string
	UserId int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type InfoType struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	SonInfoTypeList []*SonInfoType `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type SonInfoType struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	InfoTypeId int64
	FollowingProblemList []*FollowingProblems `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type FollowingProblems struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	SonInfoTypeId int64
	Select bool `xorm:"-"`
	OtherValues string
	ProblemList []*Problem `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type UserFollowingProblems struct {
	Id int64 `xorm:"pk autoincr"`
	UserId int64
	FollowingProblemId int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Problem struct {
	Id int64 `xorm:"pk autoincr"`
	FollowingProblemId int64
	Name string
	Whether bool `xorm:"-"`
	Number int `xorm:"-"`
	MaxValue int `xorm:"-"`
	MinValue int `xorm:"-"`
	Describe string `xorm:"-"`
	Describe1 string `xorm:"-"`
	Describe2 string `xorm:"-"`
	FollowingProblemList []*FollowingProblems `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type UserProblem struct {
	Id int64 `xorm:"pk autoincr"`
	UserId int64
	ProblemId int64
	Whether bool
	Number int
	MaxValue int
	MinValue int
	Describe string
	Describe1 string
	Describe2 string
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Meal struct{
	Id int `xorm:"pk autoincr"`
	MealName string
	Price int64
	Number int64
	Cycle int
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Order struct {
	Id int64 `xorm:"pk autoincr"`
	OrderType int
	OrderState int
	CustomerId int64
	CustomerName string
	NextSinglePersonId int64
	NextSinglePersonName string
	Meal string
	MealList []*Meal `xorm:"-"`
	TotalPrice int64
	Region string
	CreatedAt time.Time
	UpdatedAt time.Time
}

type ServiceOrder struct {
	Id int64  `xorm:"pk autoincr"`
	OrderId int64
	UserId int64
	Stage int
	Method string
	Cycle int
	WeightAtOrder float64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type DietInformation struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	ComponentStandard int
	Participate bool `xorm:"-"`
	FoodProblemList []*FoodProblems `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type FoodProblems struct {
	Id int64 `xorm:"pk autoincr"`
	DietInformationId int64
	Name string `xorm:"index"`
	Solt int
	OptionList []*Option `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Option struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	Value float64
	Check bool `xorm:"-"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type FoodProblemOption struct {
	Id int64 `xorm:"pk autoincr"`
	FoodProblemId int64
	OptionId string
	CreatedAt time.Time
	UpdatedAt time.Time
}

type UserDietInformation struct {
	Id int64 `xorm:"pk autoincr"`
	UserId int64
	HindamiseAruanneId int64
	DietInformationId int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type UserOption struct {
	Id int64 `xorm:"pk autoincr"`
	UserId int64
	HindamiseAruanneId int64
	FoodProblemId int64
	OptionId int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type HindamiseAruanne struct {
	Id int64 `xorm:"pk autoincr"`
	UserId int64
	FinallyRecommend string
	AccountId int64
	DepartMentId int64
	DepartMentName string
	AccountName string
	ProblemReportList []*ProblemReport `xorm:"-"`
	DietInformationList []*DietInformation `xorm:"-"`
	//DietInformationListStr string `xorm:"varchar(51200)"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

type ProblemReport struct {
	Id int64 `xorm:"pk autoincr"`
	HindamiseAruanneId int64
	FoodItems string
	FrequencyWeek string
	CopiesDay string
	DietConclusion string
	RecommendedMethod string
	CreatedAt time.Time
	UpdatedAt time.Time
}

func QueryUserInfo(uId int64)(*User, error){

	var u User
	x.Id(uId).Get(&u)

	x.Find(&u.InfoTypeList)

	for _, it := range u.InfoTypeList{
		x.Where("info_type_id = ?", it.Id).Find(it.SonInfoTypeList)
		for _, sit := range it.SonInfoTypeList {
			x.Where("son_info_type_id = ?", sit.Id).Find(sit.FollowingProblemList)
			for _, fp := range sit.FollowingProblemList {
				var ufp UserFollowingProblems
				x.Where("user_id = ?", u.Id).And("following_problem_id = ?", fp.Id).Get(&ufp)
				if ufp.Id != 0 {
					fp.Select = true
				}

				x.Where("following_problem_id = ?", fp.Id).Find(fp.ProblemList)
				for _, p := range fp.ProblemList {
					var up UserProblem
					x.Where("user_id = ?", u.Id).And("problem_id = ?", p.Id).Get(&up)
					if up.Id != 0 {
						p.Whether = up.Whether
						p.Number = up.Number
						p.MaxValue = up.MaxValue
						p.MinValue = up.MinValue
						p.Describe = up.Describe
						p.Describe1 = up.Describe1
						p.Describe2 = up.Describe2
					}

					x.Where("son_info_type_id = ?", p.Id).Find(p.FollowingProblemList)
					for _, pfp := range p.FollowingProblemList{
						var pufp UserFollowingProblems
						x.Where("user_id = ?", u.Id).And("following_problem_id = ?", pfp.Id).Get(&pufp)
						if pufp.Id != 0 {
							fp.Select = true
						}
					}
				}
			}
		}
	}
	return &u, nil
}

func QueryUserInfoAsync(uId int64)(*User, error){

	var u User
	x.Id(uId).Get(&u)

	x.Find(&u.InfoTypeList)

	var wg sync.WaitGroup
	wg.Add(10)

	for i := 0; i < 10; i++ {
		actual := i
		go func() {
			for _, it := range u.InfoTypeList[actual*3:(actual+1)*3] {
				x.Where("info_type_id = ?", it.Id).Find(it.SonInfoTypeList)
				for _, sit := range it.SonInfoTypeList {
					x.Where("son_info_type_id = ?", sit.Id).Find(sit.FollowingProblemList)
					for _, fp := range sit.FollowingProblemList {
						var ufp UserFollowingProblems
						x.Where("user_id = ?", u.Id).And("following_problem_id = ?", fp.Id).Get(&ufp)
						if ufp.Id != 0 {
							fp.Select = true
						}

						x.Where("following_problem_id = ?", fp.Id).Find(fp.ProblemList)
						for _, p := range fp.ProblemList {
							var up UserProblem
							x.Where("user_id = ?", u.Id).And("problem_id = ?", p.Id).Get(&up)
							if up.Id != 0 {
								p.Whether = up.Whether
								p.Number = up.Number
								p.MaxValue = up.MaxValue
								p.MinValue = up.MinValue
								p.Describe = up.Describe
								p.Describe1 = up.Describe1
								p.Describe2 = up.Describe2
							}

							x.Where("son_info_type_id = ?", p.Id).Find(p.FollowingProblemList)
							for _, pfp := range p.FollowingProblemList {
								var pufp UserFollowingProblems
								x.Where("user_id = ?", u.Id).And("following_problem_id = ?", pfp.Id).Get(&pufp)
								if pufp.Id != 0 {
									fp.Select = true
								}
							}
						}
					}
				}
			}

			wg.Done()
		}()
	}

	wg.Wait()

	return &u, nil
}

func InsertUser(u *User)(map[string]interface{}, error){

	x.Insert(u)
	for _, it := range u.InfoTypeList{
		for _, sit := range it.SonInfoTypeList {
			for _, fp := range sit.FollowingProblemList {
				if fp.Select {
					var ufp UserFollowingProblems
					x.Where("user_id = ?", u.Id).And("following_problem_id = ?", fp.Id).Get(&ufp)
					if ufp.Id == 0 {
						ufp.UserId = u.Id
						ufp.FollowingProblemId = fp.Id
						ufp.CreatedAt = time.Now()
						ufp.UpdatedAt = time.Now()

						x.Insert(&ufp)

						for _, p := range fp.ProblemList {
							var up UserProblem

							up.UserId = u.Id
							up.ProblemId = p.Id
							up.Number = p.Number
							up.Whether = p.Whether
							up.MaxValue = p.MaxValue
							up.MinValue = p.MinValue
							up.CreatedAt = time.Now()
							up.UpdatedAt = time.Now()

							x.Insert(&up)

							for _, pfp := range p.FollowingProblemList{
								if pfp.Select{
									var pufp UserFollowingProblems
									x.Where("user_id = ?", u.Id).And("following_problem_id = ?", pfp.Id).Get(&pufp)
									if pufp.Id == 0 {
										pufp.UserId = u.Id
										pufp.FollowingProblemId = pfp.Id
										pufp.CreatedAt = time.Now()
										pufp.UpdatedAt = time.Now()

										x.Insert(&pufp)
									}
								}else {
									var pufpe UserFollowingProblems
									x.Where("user_id = ?", u.Id).And("following_problem_id = ?", pfp.Id).Get(&pufpe)
									if pufpe.Id != 0 {
										x.Id(pufpe.Id).Delete(&pufpe)
									}
								}
							}
						}
					}
				}else {
					var ufp UserFollowingProblems
					x.Where("user_id = ?", u.Id).And("following_problem_id = ?", fp.Id).Get(&ufp)
					if ufp.Id != 0 {

						x.Id(ufp.Id).Delete(&ufp)

						for _, p := range fp.ProblemList {

							var up UserProblem
							x.Where("user_id = ?", u.Id).And("problem_id = ?", p.Id).Delete(&up)

							for _, pfp := range p.FollowingProblemList{

								var pufp UserFollowingProblems
								x.Where("user_id = ?", u.Id).And("following_problem_id = ?", pfp.Id).Delete(&pufp)
							}
						}
					}
				}
			}
		}
	}

	return map[string]interface{}{"message":"成功","code":200}, nil
}

func InsertUserAsync(u *User)(map[string]interface{}, error){

	x.Insert(u)

	var wg sync.WaitGroup
	wg.Add(10)

	for i := 0; i < 10; i++ {
		actual := i
		go func() {
			for _, it := range u.InfoTypeList[actual*3:(actual+1)*3] {
				for _, sit := range it.SonInfoTypeList {
					for _, fp := range sit.FollowingProblemList {
						if fp.Select {
							var ufp UserFollowingProblems
							x.Where("user_id = ?", u.Id).And("following_problem_id = ?", fp.Id).Get(&ufp)
							if ufp.Id == 0 {
								ufp.UserId = u.Id
								ufp.FollowingProblemId = fp.Id
								ufp.CreatedAt = time.Now()
								ufp.UpdatedAt = time.Now()

								x.Insert(&ufp)

								for _, p := range fp.ProblemList {
									var up UserProblem

									up.UserId = u.Id
									up.ProblemId = p.Id
									up.Number = p.Number
									up.Whether = p.Whether
									up.MaxValue = p.MaxValue
									up.MinValue = p.MinValue
									up.CreatedAt = time.Now()
									up.UpdatedAt = time.Now()

									x.Insert(&up)

									for _, pfp := range p.FollowingProblemList {
										if pfp.Select {
											var pufp UserFollowingProblems
											x.Where("user_id = ?", u.Id).And("following_problem_id = ?", pfp.Id).Get(&pufp)
											if pufp.Id == 0 {
												pufp.UserId = u.Id
												pufp.FollowingProblemId = pfp.Id
												pufp.CreatedAt = time.Now()
												pufp.UpdatedAt = time.Now()

												x.Insert(&pufp)
											}
										} else {
											var pufpe UserFollowingProblems
											x.Where("user_id = ?", u.Id).And("following_problem_id = ?", pfp.Id).Get(&pufpe)
											if pufpe.Id != 0 {
												x.Id(pufpe.Id).Delete(&pufpe)
											}
										}
									}
								}
							}
						} else {
							var ufp UserFollowingProblems
							x.Where("user_id = ?", u.Id).And("following_problem_id = ?", fp.Id).Get(&ufp)
							if ufp.Id != 0 {

								x.Id(ufp.Id).Delete(&ufp)

								for _, p := range fp.ProblemList {

									var up UserProblem
									x.Where("user_id = ?", u.Id).And("problem_id = ?", p.Id).Delete(&up)

									for _, pfp := range p.FollowingProblemList {

										var pufp UserFollowingProblems
										x.Where("user_id = ?", u.Id).And("following_problem_id = ?", pfp.Id).Delete(&pufp)
									}
								}
							}
						}
					}
				}
			}

			wg.Done()
		}()
	}

	wg.Wait()
	
	return map[string]interface{}{"message":"成功","code":200}, nil
}

func RecommendedMethod(u *User, oId int64, c int)(map[string]interface{}, error){

	u.LatestServiceStartTime = time.Now()
	x.Id(u.Id).Update(u)

	var newSo = ServiceOrder{
		OrderId:   oId,
		UserId:    u.Id,
		Stage:     0,
		Cycle:     c,
		WeightAtOrder: u.CurrentWeight,
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	}

	var ufp1 UserFollowingProblems
	x.Where("user_id = ?", u.Id).And("following_problem_id = ?",68 ).Get(&ufp1)
	if ufp1.Id != 0 {
		newSo.Method = "CRD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}


	var ufp2 UserFollowingProblems
	x.Where("user_id = ?", u.Id).And("following_problem_id = ?",57 ).Get(&ufp2)
	if ufp2.Id != 0 {
		newSo.Method = "LCD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	var ufp3 UserFollowingProblems
	x.Where("user_id = ?", u.Id).And("following_problem_id = ?",56 ).Get(&ufp3)
	if ufp3.Id != 0 {
		newSo.Method = "LCD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	var ufp4 UserFollowingProblems
	x.Where("user_id = ?", u.Id).And("following_problem_id = ?", 35).Get(&ufp4)
	if ufp4.Id != 0 {
		newSo.Method = "CRD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	var ufp5 UserFollowingProblems
	x.Where("user_id = ?", u.Id).And("following_problem_id = ?",30 ).Get(&ufp5)
	if ufp5.Id != 0 {
		newSo.Method = "IFD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	var ufp6 UserFollowingProblems
	x.Join("INNER", "following_problems", "following_problems.id = user_following_problems.following_problem_id").
		Where("user_following_problems.user_id = ?", u.Id).
		And("following_problems.son_info_type_id = ?",9).
		Get(&ufp6)
	if ufp6.Id == 0 {
		newSo.Method = "CRD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	var ufp7 UserFollowingProblems
	x.Where("user_id = ?", u.Id).And("following_problem_id = ?", 41).Get(&ufp7)
	if ufp7.Id != 0{
		newSo.Method = "CRD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	var ufp8 UserFollowingProblems
	x.Where("user_id = ?", u.Id).And("following_problem_id = ?", 42).Get(&ufp8)
	if ufp7.Id != 0{
		newSo.Method = "CRD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	var ufp9 UserFollowingProblems
	x.Where("user_id = ?", u.Id).And("following_problem_id = ?", 43).Get(&ufp9)
	if ufp9.Id != 0{
		newSo.Method = "LCD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	var ufp10 UserFollowingProblems
	x.Where("user_id = ?", u.Id).And("following_problem_id = ?", 44).Get(&ufp10)
	if ufp9.Id != 0{
		newSo.Method = "LCD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	var ufp11 UserFollowingProblems
	x.Where("user_id = ?", u.Id).And("following_problem_id = ?", 45).Get(&ufp11)
	if ufp11.Id != 0{
		newSo.Method = "IFD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	var ufp12 UserProblem
	x.Where("user_id = ?", u.Id).And("following_problem_id = ?", 46).Get(&ufp12)
	if ufp12.Id != 0 {
		newSo.Method = "IFD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	var ufp13 UserProblem
	x.Where("user_id = ?", u.Id).And("following_problem_id = ?", 47).Get(&ufp13)
	if ufp13.Id != 0 {
		newSo.Method = "IFD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	return map[string]interface{}{"code":400, "message":"找不到合适的方案"}, nil

}

func RecommendedMethod1(u *User, oId int64, c int)(map[string]interface{}, error){

	var newSo = ServiceOrder{
		OrderId:   oId,
		UserId:    u.Id,
		Stage:     1,
		Cycle:     c,
		WeightAtOrder: u.CurrentWeight,
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	}

	var ufp1 UserFollowingProblems
	x.Where("user_id = ?", u.Id).And("following_problem_id = ?",68 ).Get(&ufp1)
	if ufp1.Id != 0 {

		newSo.Method = "LCD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	var ufp2 UserFollowingProblems
	x.Where("user_id = ?", u.Id).And("following_problem_id = ?",57 ).Get(&ufp2)
	if ufp2.Id != 0 {
		newSo.Method = "CRD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	var ufp3 UserFollowingProblems
	x.Where("user_id = ?", u.Id).And("following_problem_id = ?",56 ).Get(&ufp3)
	if ufp3.Id != 0 {
		newSo.Method = "LCD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	var ha HindamiseAruanne
	x.Where("user_id").Desc("created_at").Limit(1).Get(&ha)
	if ha.FinallyRecommend == "LCD"{
		newSo.Method = "LCD"

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}else if ha.FinallyRecommend == "IFD"{

		var oso ServiceOrder
		x.Where("user_id = ?", u.Id).Desc("created_at").Limit(1).Get(&oso)
		if oso.Method == "IFD"{
			newSo.Method = "LCD"

			x.Insert(&newSo)
			return map[string]interface{}{"code":200, "message":"成功"}, nil
		}else {
			newSo.Method = "IFD"

			x.Insert(&newSo)
			return map[string]interface{}{"code":200, "message":"成功"}, nil
		}
	}else{
		var oso ServiceOrder
		x.Where("user_id = ?", u.Id).Desc("created_at").Limit(1).Get(&oso)
		if oso.Method == "CRD"{
			newSo.Method = "IFD"

			x.Insert(&newSo)
			return map[string]interface{}{"code":200, "message":"成功"}, nil
		}else {
			newSo.Method = "CRD"

			x.Insert(&newSo)
			return map[string]interface{}{"code":200, "message":"成功"}, nil
		}
	}

	return map[string]interface{}{"code":400, "message":"找不到合适的方案"}, nil
}

func ServiceOrderPlacing(uId int64, ot int, aId int64, m *Meal)(map[string]interface{}, error){

	var newOrder = Order{
		OrderType:            ot,
		OrderState:           0,
		CustomerId:           uId,
		NextSinglePersonId:   aId,
		CreatedAt:            time.Now(),
		UpdatedAt:            time.Now(),
	}
	x.Insert(&newOrder)

	var u User
	x.Id(uId).Get(&u)

	if u.Bmi < 18.5{

		var newSo = ServiceOrder{
			OrderId:   newOrder.Id,
			UserId:    u.Id,
			Stage:     2,
			Method:    "CRD",
			Cycle:     m.Cycle,
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
		}

		x.Insert(&newSo)
		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	var ncd NewCustomerDistribution
	x.Where("user_id = ?", u.Id).Get(&ncd)
	var dcd DCustomerDistribution
	x.Where("user_id = ?", u.Id).Get(&dcd)
	if ncd.Id != 0 && dcd.Id != 0{
		return RecommendedMethod(&u, newOrder.Id, m.Cycle)
	}

	var oList []*Order
	x.Where("customer_id = ?", u.Id).
		And("order_state = ?", 39).
		And("created_at < ", time.Now().AddDate(0,0,-90)).
		In("order_type", []int{1, 3, 10}).
		Find(&oList)
	if len(oList) == 0{
		return RecommendedMethod(&u, newOrder.Id, m.Cycle)
	}

	var so ServiceOrder
	x.Join("INNER", "order", "order.id = service_order.order_id").
		Where("order.customer_id = ?", u.Id).
		And("order.order_type = ?", 10).
		And("created_at >= ", time.Now().AddDate(0,0,-90)).
		Desc("order.created_at").
		Limit(1).
		Get(&so)
	if so.Stage == 0 || so.Id == 0 {
		RecommendedMethod1(&u, newOrder.Id, m.Cycle)
	}else if so.Stage == 1{

		var sov ServiceOrder
		total, err := x.Where("user_id = ?", ).And("created_at >= ", u.LatestServiceStartTime).SumInt(sov, "cycle")
		if err != nil{
			return map[string]interface{}{"code":500, "message":"失败"}, err
		}
		if total >= 28 {
			var newSo = ServiceOrder{
				OrderId:   newOrder.Id,
				UserId:    u.Id,
				Stage:     2,
				Cycle:     m.Cycle,
				WeightAtOrder: u.CurrentWeight,
				CreatedAt: time.Now(),
				UpdatedAt: time.Now(),
			}

			var ufp1 UserFollowingProblems
			x.Where("user_id = ?", uId).And("following_problem_id = ?",68 ).Get(&ufp1)
			if ufp1.Id != 0 {

				newSo.Method = "CRD"

				x.Insert(&newSo)
				return map[string]interface{}{"code":200, "message":"成功"}, nil
			}

			var ufp2 UserFollowingProblems
			x.Where("user_id = ?", uId).And("following_problem_id = ?",57 ).Get(&ufp2)
			if ufp2.Id != 0 {
				newSo.Method = "IFD"

				x.Insert(&newSo)
				return map[string]interface{}{"code":200, "message":"成功"}, nil
			}

			var ufp3 UserFollowingProblems
			x.Where("user_id = ?", uId).And("following_problem_id = ?",56 ).Get(&ufp3)
			if ufp3.Id != 0 {
				newSo.Method = "CRD"

				x.Insert(&newSo)
				return map[string]interface{}{"code":200, "message":"成功"}, nil
			}

			if (u.InitialBodyWeight-u.CurrentWeight)/(u.InitialBodyWeight-u.TargetWeight) < 0.7 {
				newSo.Method = "IFD"

				x.Insert(&newSo)
				return map[string]interface{}{"code":200, "message":"成功"}, nil
			}else {
				newSo.Method = "CRD"

				x.Insert(&newSo)
				return map[string]interface{}{"code":200, "message":"成功"}, nil
			}
		}else {
			RecommendedMethod1(&u, newOrder.Id, m.Cycle)
		}

	}else if so.Stage == 2{

		if  (u.InitialBodyWeight-u.CurrentWeight)/(u.InitialBodyWeight-u.TargetWeight) >= 0.9 || u.TargetWeight-u.CurrentWeight <= 3{

			var newSo = ServiceOrder{
				OrderId:   newOrder.Id,
				UserId:    u.Id,
				Stage:     3,
				Method:    "CRD",
				Cycle:     m.Cycle,
				CreatedAt: time.Now(),
				UpdatedAt: time.Now(),
			}
			x.Insert(&newSo)

			return map[string]interface{}{"code":200, "message":"成功"}, nil
		}else {
			return RecommendedMethod(&u, newOrder.Id, m.Cycle)
		}

	}else if so.Stage == 3{

		var so ServiceOrder
		x.Join("INNER", "order", "order.id = service_order.order_id").
			Where("order.customer_id = ?", u.Id).
			And("order.order_typr = ?", 10).
			And("service_order.stage = ?", 3).
			Desc("order.created_at").
			Limit(1).
			Get(&so)
		if u.CurrentWeight - so.WeightAtOrder>= 4{
			return RecommendedMethod(&u, newOrder.Id, m.Cycle)
		}else {
			var newSo = ServiceOrder{
				OrderId:   newOrder.Id,
				UserId:    u.Id,
				Stage:     3,
				Method:    "CRD",
				Cycle:     m.Cycle,
				WeightAtOrder: u.CurrentWeight,
				CreatedAt: time.Now(),
				UpdatedAt: time.Now(),
			}
			x.Insert(&newSo)

			return map[string]interface{}{"code":200, "message":"成功"}, nil
		}
	}

	x.Id(newOrder.Id).Delete(&newOrder)
	return map[string]interface{}{"message":"找不到合适的方案","code":400}, nil

}

func BubbleSort(arr []int) []int{
	for i := 0; i < len(arr)-1; i++ {
		for j := 0; j < len(arr)-i-1; j++ {
			if arr[j] > arr[j+1] {
				arr[j], arr[j+1] = arr[j+1], arr[j]
			}
		}
	}
	return arr
}

func (dietInformation *DietInformation)Submit(uId int64, diList []*DietInformation, a *Account, dietInformationListStr string)(map[string]interface{}, error){

	w := new(utils.Worker)

	var u User
	x.Id(uId).Get(&u)

	var ha = HindamiseAruanne{
		Id:     w.GetId(),
		UserId: u.Id,
		AccountId: a.AccountId,
		AccountName: a.AccountName,
		DepartMentId: a.DepartMentId,
		DepartMentName: a.DepartMentName,
		//DietInformationListStr: dietInformationListStr,
		CreatedAt:         time.Now(),
		UpdatedAt:         time.Now(),
	}
	x.Insert(&ha)

	for _, di := range diList{

		var pr = ProblemReport{
			Id:                w.GetId(),
			FoodItems:         di.Name,
			HindamiseAruanneId:  ha.Id,
		}

		if di.Participate == true{

			var udi = UserDietInformation{
				Id:                w.GetId(),
				UserId:            u.Id,
				HindamiseAruanneId: ha.Id,
				DietInformationId: di.Id,
				CreatedAt:         time.Now(),
				UpdatedAt:         time.Now(),
			}
			x.Insert(&udi)

			var intake float64 = 1
			for _, fb:= range di.FoodProblemList {

				for _, o := range fb.OptionList {

					if o.Check == true{
						if fb.Id != 324228578927443970 && fb.Id != 324228578927443979 && di.Id != 324225322562093061 && di.Id != 324225322562093066{
							switch fb.Solt {
							case 1:
								pr.FrequencyWeek = o.Name
							case 2:
								pr.CopiesDay = o.Name
							}

							intake *= o.Value

						}else {

							switch di.Id {
							case 324225322562093061:

								pr.FrequencyWeek = "是"
								pr.CopiesDay = o.Name

								switch o.Id {
								case 324234845406363666:
									pr.DietConclusion = "全素食：蛋白质摄入不足，对机体抗病能力影响大，可能造成消瘦，免疫机能较弱，肌肉萎缩"
								case 324234845406363667:
									pr.DietConclusion = "蛋素食：钙、维生素B12摄入不足，可能造成骨质疏松、疲劳"
								case 324234845406363669:
									pr.DietConclusion = "蛋奶素食: 铁、维生素B12摄入不足，可能造成贫血、疲劳"
								case 324234845406363668:
									pr.DietConclusion = "奶素食：维生素B12摄入不足，可能造成疲劳"
								}
								pr.RecommendedMethod = "不作为判断依据"

							case 324225322562093066:

								pr.FrequencyWeek = o.Name

								if o.Id != 324234845406363670{
									pr.DietConclusion = "出差时间较多，饮食变化性较大"
									pr.RecommendedMethod = "IFD"
								}
							}
						}

						var uo = UserOption{
							Id:                 w.GetId(),
							UserId:             u.Id,
							HindamiseAruanneId: ha.Id,
							FoodProblemId:      fb.Id,
							OptionId:           o.Id,
							CreatedAt:          time.Now(),
							UpdatedAt:          time.Now(),
						}
						x.Insert(&uo)

					}
				}
			}

			intake = intake * float64(di.ComponentStandard) / 7
			switch di.Id {
			case 324225322562093056:
				if intake < 250 {
					pr.DietConclusion = "摄入量<250克：谷物摄入过少，有可能出现低血糖，产生头晕、脑功能障碍等问题。"
					pr.RecommendedMethod = "IFD"
				} else if intake >= 250 && intake <= 400 {
					pr.DietConclusion = "摄入量250-400克：摄入量正常。"
					pr.RecommendedMethod = "LCD"
				} else {
					pr.DietConclusion = "摄入粗粮是好的饮食习惯。粗粮含有丰富的膳食纤维，能够增加饱腹感，以及预防和治疗便秘。"
					pr.RecommendedMethod = "LCD"
				}
			case 324225322562093057:
				if intake < 200 {
					pr.DietConclusion = "摄入量<200克：水果摄入过少，有可能影响身体水分、膳食纤维、维生素C、维生素E摄入。"
					pr.RecommendedMethod = "不作为判断依据"
				} else if intake >= 200 && intake <= 350 {
					pr.DietConclusion = "摄入量200-350克：摄入量正常。"
					pr.RecommendedMethod = "不作为判断依据"
				} else {
					pr.DietConclusion = "摄入量>350克：水果摄入过多，增加糖摄入，有可能增加体内脂肪储存。"
					pr.RecommendedMethod = "LCD"
				}
			case 324225322562093058:
				if intake < 300 {
					pr.DietConclusion = "摄入量<300克：蔬菜摄入过少，膳食纤维摄取不足，有可能导致便秘。"
					pr.RecommendedMethod = "IFD"
				} else if intake >= 300 && intake <= 500 {
					pr.DietConclusion = "摄入量300-500克：摄入量正常。"
					pr.RecommendedMethod = "IFD"
				} else {
					pr.DietConclusion = "摄入量>500克：蔬菜摄入过多，有可能造成不易消化，阻碍钙、锌吸收。"
					pr.RecommendedMethod = "LCD"
				}
			case 324225322562093059:
				if intake < 300 {
					pr.DietConclusion = "摄入量<300克：钙、维生素B12摄入不足，可能造成骨质疏松、疲劳。"
					pr.RecommendedMethod = "LCD"
				} else if intake == 300{
					pr.DietConclusion = "摄入量300克：摄入量正常。"
					pr.RecommendedMethod = "LCD"
				}else {
					pr.DietConclusion = "摄入有点多，适量就好。"
					pr.RecommendedMethod = "LCD"
				}
			case 324225322562093060:
				if intake < 40 {
					pr.DietConclusion = "摄入量＜40g,蛋类是优质蛋白来源，人体吸收比例高。建议摄入1周5天，每天1个蛋，保证营养均衡摄入。"
					pr.RecommendedMethod = "LCD"
				} else if intake >= 40 && intake <= 50 {
					pr.DietConclusion = "摄入量40-50克：摄入量正常。"
					pr.RecommendedMethod = "LCD"
				} else {
					pr.DietConclusion = "摄入量>50克：蛋类摄入过多，蛋黄中含有大量胆固醇有可能导致血脂升高，增加冠心病几率。"
					pr.RecommendedMethod = "CRD"
				}
			case 324225322562093062:
				if intake < 40 {
					pr.DietConclusion = "摄入量<40克：肉类摄入过少，蛋白质摄入不足，对机体抗病能力影响大，可能造成消瘦，免疫机能较弱，肌肉萎缩；铁、维生素B12摄入不足，可能造成贫血、疲劳。"
					pr.RecommendedMethod = "LCD"
				} else if intake >= 40 && intake <= 75 {
					pr.DietConclusion = "摄入量40-75克：摄入量正常。"
					pr.RecommendedMethod = "LCD"
				} else {
					pr.DietConclusion = "摄入量>75克：肉类摄入过多，饱和脂肪摄入过量，有可能造成高血脂，引发慢性疾病。"
					pr.RecommendedMethod = "CRD"
				}
			case 324225322562093063:
				if intake < 40 {
					pr.DietConclusion = "摄入量〈40克：摄入量过少。"
					pr.RecommendedMethod = "LCD"
				} else if intake >= 40 && intake <= 75 {
					pr.DietConclusion = "摄入量40-75克：摄入量正常。"
					pr.RecommendedMethod = "LCD"
				} else {
					pr.DietConclusion = "摄入量>75克：鱼虾摄入过多，可能导致尿酸生成过多，从而增加痛风患病率。"
					pr.RecommendedMethod = "CRD"
				}
			case 324225322562093064:
				if intake < 25 {
					pr.DietConclusion = "摄入量<25克大豆：摄入量过少。"
					pr.RecommendedMethod = "LCD"
				} else if intake >= 25 && intake <= 35 {
					pr.DietConclusion = "摄入量25-35克大豆：摄入量正常。"
					pr.RecommendedMethod = "LCD"
				} else {
					pr.DietConclusion = "摄入量>35克大豆：豆制品摄入过多，有可能引起消化不良，造成腹胀、腹泻等症状。"
					pr.RecommendedMethod = "CRD"
				}
			case 324225322562093065:
				if u.Sex == 1{
					if intake < 15 {
						pr.DietConclusion = "女性 < 15克酒精，摄入正常"
						pr.RecommendedMethod = "不作为判断依据"
					}else {
						pr.DietConclusion = "女性 >= 15克酒精，摄入过量"
						pr.RecommendedMethod = "IFD"
					}
				}else {
					if intake < 25 {
						pr.DietConclusion = "男性 < 25克酒精，摄入正常"
						pr.RecommendedMethod = "不作为判断依据"
					}else {
						pr.DietConclusion = "男性 >= 25克酒精，摄入过量"
						pr.RecommendedMethod = "IFD"
					}
				}
			}

		}else {
			pr.FrequencyWeek = ""
			pr.CopiesDay = ""

			switch di.Id {
			case 324225322562093056:
				pr.DietConclusion = "谷物摄入过少，有可能出现低血糖，产生头晕、脑功能障碍等问题。"
				pr.RecommendedMethod  = "IFD"
			case 324225322562093057:
				pr.DietConclusion = "水果摄入过少，有可能影响身体水分、维生素C、维生素E摄入。"
				pr.RecommendedMethod  = "不作为判断依据"
			case 324225322562093058:
				pr.DietConclusion = "蔬菜摄入过少，膳食纤维摄取不足，有可能导致便秘"
				pr.RecommendedMethod  = "IFD"
			case 324225322562093059:
				pr.DietConclusion = "奶制品摄入过少，钙、维生素B12摄入不足，可能造成骨质疏松、疲劳。"
				pr.RecommendedMethod  = "LCD"
			case 324225322562093060:
				pr.DietConclusion = "不吃，蛋类是优质蛋白来源，人体吸收比例高。建议摄入1周5天，每天1个蛋，保证营养均衡摄入。"
				pr.RecommendedMethod  = "LCD"
			case 324225322562093062:
				pr.DietConclusion = "肉类摄入过少：蛋白质摄入不足，对机体抗病能力影响大，可能造成消瘦，免疫机能较弱，肌肉萎缩；铁、维生素B12摄入不足，可能造成贫血、疲劳。"
				pr.RecommendedMethod  = "LCD"
			case 324225322562093063:
				pr.DietConclusion = "不吃，健康的饮食讲究种类多样化，营养均衡，而水产品是良好的蛋白质来源，建议适量食用。"
				pr.RecommendedMethod  = "LCD"
			case 324225322562093064:
				pr.DietConclusion = "不吃，健康的饮食讲究种类多样化，营养均衡，而大豆及豆制品是良好的蛋白质来源，建议适量食用。"
				pr.RecommendedMethod  = "LCD"
			case 324225322562093065:
				pr.DietConclusion = "饮酒有害健康，不喝为妙。"
				pr.RecommendedMethod  = "不作为判断依据"
			case 324225322562093066:
				pr.DietConclusion = "无出差，饮食变化性较少，相对稳定。"
				pr.RecommendedMethod  = "不作为判断依据"
			}
		}

		pr.CreatedAt = time.Now()
		pr.UpdatedAt = time.Now()
		x.Insert(&pr)
	}

	var prList []*ProblemReport
	x.Where("hindamise_aruanne_id = ?", ha.Id).Find(&prList)

	var lcdTem int
	var ifdTem int
	var crdTem int
	for _, prv := range prList{
		if prv.RecommendedMethod == "LCD"{
			lcdTem += 1
		}
		if prv.RecommendedMethod == "IFD"{
			ifdTem += 1
		}
		if prv.RecommendedMethod == "CRD"{
			crdTem += 1
		}
	}
	var temList = []int{lcdTem, ifdTem, crdTem}
	fmt.Println("temList：", temList)

	list := BubbleSort(temList)
	fmt.Println("list：", list)

	if list[len(list)-1] == lcdTem{
		ha.FinallyRecommend = "LCD"
	}else {
		if list[len(list)-1] == ifdTem {
			ha.FinallyRecommend = "IFD"
		}else {
			ha.FinallyRecommend = "CRD"
		}
	}
	x.Id(ha.Id).Update(&ha)

	return map[string]interface{}{"code":200, "message":"成功"}, nil
}

func (dietInformation *DietInformation)SubmitAsync(uId int64, diList []*DietInformation, a *Account, dietInformationListStr string)(map[string]interface{}, error){

	w := new(utils.Worker)

	var u User
	x.Id(uId).Get(&u)

	var ha = HindamiseAruanne{
		Id:     w.GetId(),
		UserId: u.Id,
		AccountId: a.AccountId,
		AccountName: a.AccountName,
		DepartMentId: a.DepartMentId,
		DepartMentName: a.DepartMentName,
		//DietInformationListStr: dietInformationListStr,
		CreatedAt:         time.Now(),
		UpdatedAt:         time.Now(),
	}
	x.Insert(&ha)

	p := pool.NewSimplePoll(4)
	for i := 0; i < 4; i++ {
		var finalI int = i
		p.Add(func(){
			var sliceDilist []*DietInformation
			if finalI == 3{
				sliceDilist = diList[finalI*3:len(diList)]
			}else {
				sliceDilist = diList[finalI*3:(finalI+1)*3]
			}
			for _, di := range sliceDilist {

				var pr = ProblemReport{
					Id:                 w.GetId(),
					FoodItems:          di.Name,
					HindamiseAruanneId: ha.Id,
				}

				if di.Participate == true {

					var udi = UserDietInformation{
						Id:                 w.GetId(),
						UserId:             u.Id,
						HindamiseAruanneId: ha.Id,
						DietInformationId:  di.Id,
						CreatedAt:          time.Now(),
						UpdatedAt:          time.Now(),
					}
					x.Insert(&udi)

					var intake float64 = 1
					for _, fb := range di.FoodProblemList {

						for _, o := range fb.OptionList {

							if o.Check == true {
								if fb.Id != 324228578927443970 && fb.Id != 324228578927443979 && di.Id != 324225322562093061 && di.Id != 324225322562093066 {
									switch fb.Solt {
									case 1:
										pr.FrequencyWeek = o.Name
									case 2:
										pr.CopiesDay = o.Name
									}

									intake *= o.Value

								} else {

									switch di.Id {
									case 324225322562093061:

										pr.FrequencyWeek = "是"
										pr.CopiesDay = o.Name

										switch o.Id {
										case 324234845406363666:
											pr.DietConclusion = "全素食：蛋白质摄入不足，对机体抗病能力影响大，可能造成消瘦，免疫机能较弱，肌肉萎缩"
										case 324234845406363667:
											pr.DietConclusion = "蛋素食：钙、维生素B12摄入不足，可能造成骨质疏松、疲劳"
										case 324234845406363669:
											pr.DietConclusion = "蛋奶素食: 铁、维生素B12摄入不足，可能造成贫血、疲劳"
										case 324234845406363668:
											pr.DietConclusion = "奶素食：维生素B12摄入不足，可能造成疲劳"
										}
										pr.RecommendedMethod = "不作为判断依据"

									case 324225322562093066:

										pr.FrequencyWeek = o.Name

										if o.Id != 324234845406363670 {
											pr.DietConclusion = "出差时间较多，饮食变化性较大"
											pr.RecommendedMethod = "IFD"
										}
									}
								}

								var uo = UserOption{
									Id:                 w.GetId(),
									UserId:             u.Id,
									HindamiseAruanneId: ha.Id,
									FoodProblemId:      fb.Id,
									OptionId:           o.Id,
									CreatedAt:          time.Now(),
									UpdatedAt:          time.Now(),
								}
								x.Insert(&uo)

							}
						}
					}

					intake = intake * float64(di.ComponentStandard) / 7
					switch di.Id {
					case 324225322562093056:
						if intake < 250 {
							pr.DietConclusion = "摄入量<250克：谷物摄入过少，有可能出现低血糖，产生头晕、脑功能障碍等问题。"
							pr.RecommendedMethod = "IFD"
						} else if intake >= 250 && intake <= 400 {
							pr.DietConclusion = "摄入量250-400克：摄入量正常。"
							pr.RecommendedMethod = "LCD"
						} else {
							pr.DietConclusion = "摄入粗粮是好的饮食习惯。粗粮含有丰富的膳食纤维，能够增加饱腹感，以及预防和治疗便秘。"
							pr.RecommendedMethod = "LCD"
						}
					case 324225322562093057:
						if intake < 200 {
							pr.DietConclusion = "摄入量<200克：水果摄入过少，有可能影响身体水分、膳食纤维、维生素C、维生素E摄入。"
							pr.RecommendedMethod = "不作为判断依据"
						} else if intake >= 200 && intake <= 350 {
							pr.DietConclusion = "摄入量200-350克：摄入量正常。"
							pr.RecommendedMethod = "不作为判断依据"
						} else {
							pr.DietConclusion = "摄入量>350克：水果摄入过多，增加糖摄入，有可能增加体内脂肪储存。"
							pr.RecommendedMethod = "LCD"
						}
					case 324225322562093058:
						if intake < 300 {
							pr.DietConclusion = "摄入量<300克：蔬菜摄入过少，膳食纤维摄取不足，有可能导致便秘。"
							pr.RecommendedMethod = "IFD"
						} else if intake >= 300 && intake <= 500 {
							pr.DietConclusion = "摄入量300-500克：摄入量正常。"
							pr.RecommendedMethod = "IFD"
						} else {
							pr.DietConclusion = "摄入量>500克：蔬菜摄入过多，有可能造成不易消化，阻碍钙、锌吸收。"
							pr.RecommendedMethod = "LCD"
						}
					case 324225322562093059:
						if intake < 300 {
							pr.DietConclusion = "摄入量<300克：钙、维生素B12摄入不足，可能造成骨质疏松、疲劳。"
							pr.RecommendedMethod = "LCD"
						} else if intake == 300 {
							pr.DietConclusion = "摄入量300克：摄入量正常。"
							pr.RecommendedMethod = "LCD"
						} else {
							pr.DietConclusion = "摄入有点多，适量就好。"
							pr.RecommendedMethod = "LCD"
						}
					case 324225322562093060:
						if intake < 40 {
							pr.DietConclusion = "摄入量＜40g,蛋类是优质蛋白来源，人体吸收比例高。建议摄入1周5天，每天1个蛋，保证营养均衡摄入。"
							pr.RecommendedMethod = "LCD"
						} else if intake >= 40 && intake <= 50 {
							pr.DietConclusion = "摄入量40-50克：摄入量正常。"
							pr.RecommendedMethod = "LCD"
						} else {
							pr.DietConclusion = "摄入量>50克：蛋类摄入过多，蛋黄中含有大量胆固醇有可能导致血脂升高，增加冠心病几率。"
							pr.RecommendedMethod = "CRD"
						}
					case 324225322562093062:
						if intake < 40 {
							pr.DietConclusion = "摄入量<40克：肉类摄入过少，蛋白质摄入不足，对机体抗病能力影响大，可能造成消瘦，免疫机能较弱，肌肉萎缩；铁、维生素B12摄入不足，可能造成贫血、疲劳。"
							pr.RecommendedMethod = "LCD"
						} else if intake >= 40 && intake <= 75 {
							pr.DietConclusion = "摄入量40-75克：摄入量正常。"
							pr.RecommendedMethod = "LCD"
						} else {
							pr.DietConclusion = "摄入量>75克：肉类摄入过多，饱和脂肪摄入过量，有可能造成高血脂，引发慢性疾病。"
							pr.RecommendedMethod = "CRD"
						}
					case 324225322562093063:
						if intake < 40 {
							pr.DietConclusion = "摄入量〈40克：摄入量过少。"
							pr.RecommendedMethod = "LCD"
						} else if intake >= 40 && intake <= 75 {
							pr.DietConclusion = "摄入量40-75克：摄入量正常。"
							pr.RecommendedMethod = "LCD"
						} else {
							pr.DietConclusion = "摄入量>75克：鱼虾摄入过多，可能导致尿酸生成过多，从而增加痛风患病率。"
							pr.RecommendedMethod = "CRD"
						}
					case 324225322562093064:
						if intake < 25 {
							pr.DietConclusion = "摄入量<25克大豆：摄入量过少。"
							pr.RecommendedMethod = "LCD"
						} else if intake >= 25 && intake <= 35 {
							pr.DietConclusion = "摄入量25-35克大豆：摄入量正常。"
							pr.RecommendedMethod = "LCD"
						} else {
							pr.DietConclusion = "摄入量>35克大豆：豆制品摄入过多，有可能引起消化不良，造成腹胀、腹泻等症状。"
							pr.RecommendedMethod = "CRD"
						}
					case 324225322562093065:
						if u.Sex == 1 {
							if intake < 15 {
								pr.DietConclusion = "女性 < 15克酒精，摄入正常"
								pr.RecommendedMethod = "不作为判断依据"
							} else {
								pr.DietConclusion = "女性 >= 15克酒精，摄入过量"
								pr.RecommendedMethod = "IFD"
							}
						} else {
							if intake < 25 {
								pr.DietConclusion = "男性 < 25克酒精，摄入正常"
								pr.RecommendedMethod = "不作为判断依据"
							} else {
								pr.DietConclusion = "男性 >= 25克酒精，摄入过量"
								pr.RecommendedMethod = "IFD"
							}
						}
					}

				} else {
					pr.FrequencyWeek = ""
					pr.CopiesDay = ""

					switch di.Id {
					case 324225322562093056:
						pr.DietConclusion = "谷物摄入过少，有可能出现低血糖，产生头晕、脑功能障碍等问题。"
						pr.RecommendedMethod = "IFD"
					case 324225322562093057:
						pr.DietConclusion = "水果摄入过少，有可能影响身体水分、维生素C、维生素E摄入。"
						pr.RecommendedMethod = "不作为判断依据"
					case 324225322562093058:
						pr.DietConclusion = "蔬菜摄入过少，膳食纤维摄取不足，有可能导致便秘"
						pr.RecommendedMethod = "IFD"
					case 324225322562093059:
						pr.DietConclusion = "奶制品摄入过少，钙、维生素B12摄入不足，可能造成骨质疏松、疲劳。"
						pr.RecommendedMethod = "LCD"
					case 324225322562093060:
						pr.DietConclusion = "不吃，蛋类是优质蛋白来源，人体吸收比例高。建议摄入1周5天，每天1个蛋，保证营养均衡摄入。"
						pr.RecommendedMethod = "LCD"
					case 324225322562093062:
						pr.DietConclusion = "肉类摄入过少：蛋白质摄入不足，对机体抗病能力影响大，可能造成消瘦，免疫机能较弱，肌肉萎缩；铁、维生素B12摄入不足，可能造成贫血、疲劳。"
						pr.RecommendedMethod = "LCD"
					case 324225322562093063:
						pr.DietConclusion = "不吃，健康的饮食讲究种类多样化，营养均衡，而水产品是良好的蛋白质来源，建议适量食用。"
						pr.RecommendedMethod = "LCD"
					case 324225322562093064:
						pr.DietConclusion = "不吃，健康的饮食讲究种类多样化，营养均衡，而大豆及豆制品是良好的蛋白质来源，建议适量食用。"
						pr.RecommendedMethod = "LCD"
					case 324225322562093065:
						pr.DietConclusion = "饮酒有害健康，不喝为妙。"
						pr.RecommendedMethod = "不作为判断依据"
					case 324225322562093066:
						pr.DietConclusion = "无出差，饮食变化性较少，相对稳定。"
						pr.RecommendedMethod = "不作为判断依据"
					}
				}

				pr.CreatedAt = time.Now()
				pr.UpdatedAt = time.Now()
				x.Insert(&pr)
			}
		})
	}
	p.Run()

	var prList []*ProblemReport
	x.Where("hindamise_aruanne_id = ?", ha.Id).Find(&prList)

	var lcdTem int
	var ifdTem int
	var crdTem int
	for _, prv := range prList{
		if prv.RecommendedMethod == "LCD"{
			lcdTem += 1
		}
		if prv.RecommendedMethod == "IFD"{
			ifdTem += 1
		}
		if prv.RecommendedMethod == "CRD"{
			crdTem += 1
		}
	}
	var temList = []int{lcdTem, ifdTem, crdTem}
	fmt.Println("temList：", temList)

	list := BubbleSort(temList)
	fmt.Println("list：", list)

	if list[len(list)-1] == lcdTem{
		ha.FinallyRecommend = "LCD"
	}else {
		if list[len(list)-1] == ifdTem {
			ha.FinallyRecommend = "IFD"
		}else {
			ha.FinallyRecommend = "CRD"
		}
	}
	x.Id(ha.Id).Update(&ha)

	return map[string]interface{}{"code":200, "message":"成功"}, nil
}

func (dietInformation *DietInformation)ViewReport(uId int64)([]*HindamiseAruanne, error){

	var haList []*HindamiseAruanne
	x.Where("user_id = ?", uId).Find(&haList)
	for _, ha := range haList{
		x.Where("hindamise_aruanne_id = ?", ha.Id).Find(&ha.ProblemReportList)

		//jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal([]byte(ha.DietInformationListStr), &ha.DietInformationList)

		x.Find(&ha.DietInformationList)
		for _, di := range ha.DietInformationList{

			var udi UserDietInformation
			x.Where("user_id = ?", uId).And("hindamise_aruanne_id = ?", ha.Id).And("diet_information_id = ?", di.Id).Get(&udi)
			if udi.Id != 0{
				di.Participate = true
			}

			x.Where("diet_information_id = ?", di.Id).Find(&di.FoodProblemList)

			for _, fb := range di.FoodProblemList{

				x.Join("INNER", "food_problem_option", "food_problem_option.option_id = `option`.id").Where("food_problem_option.food_problem_id = ?", fb.Id).Find(&fb.OptionList)
				for _, o := range fb.OptionList{

					var uo UserOption
					x.Where("user_id = ?", uId).And("hindamise_aruanne_id = ?", ha.Id).And("option_id = ?", o.Id).And("food_problem_id = ?", fb.Id).Get(&uo)
					if uo.Id != 0{
						o.Check = true
					}
				}
			}
		}
	}

	return haList, nil
}

func (dietInformation *DietInformation)ViewReportAsync(uId int64)([]*HindamiseAruanne, error){

	var haList []*HindamiseAruanne
	x.Where("user_id = ?", uId).Find(&haList)

	p := pool.NewSimplePoll(4)
	for i := 0; i < 4; i++ {
		var finalI int = i
		p.Add(func(){
			var sliceHaList []*HindamiseAruanne
			if finalI == 3{
				sliceHaList = haList[finalI*3:len(haList)]
			}else {
				sliceHaList = haList[finalI*3:(finalI+1)*3]
			}
			for _, ha := range sliceHaList{
				x.Where("hindamise_aruanne_id = ?", ha.Id).Find(&ha.ProblemReportList)

				//jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal([]byte(ha.DietInformationListStr), &ha.DietInformationList)

				x.Find(&ha.DietInformationList)
				for _, di := range ha.DietInformationList{

					var udi UserDietInformation
					x.Where("user_id = ?", uId).And("hindamise_aruanne_id = ?", ha.Id).And("diet_information_id = ?", di.Id).Get(&udi)
					if udi.Id != 0{
						di.Participate = true
					}

					x.Where("diet_information_id = ?", di.Id).Find(&di.FoodProblemList)

					for _, fb := range di.FoodProblemList{

						x.Join("INNER", "food_problem_option", "food_problem_option.option_id = `option`.id").Where("food_problem_option.food_problem_id = ?", fb.Id).Find(&fb.OptionList)
						for _, o := range fb.OptionList{

							var uo UserOption
							x.Where("user_id = ?", uId).And("hindamise_aruanne_id = ?", ha.Id).And("option_id = ?", o.Id).And("food_problem_id = ?", fb.Id).Get(&uo)
							if uo.Id != 0{
								o.Check = true
							}
						}
					}
				}
			}
		})
	}
	p.Run()

	return haList, nil
}

func (dietInformation *DietInformation)QueryDietInformation()([]*DietInformation, error) {

	var diList []*DietInformation

	x.Find(&diList)
	for _, di := range diList{
		x.Where("diet_information_id = ?", di.Id).Find(&di.FoodProblemList)
		for _, fp := range di.FoodProblemList{
			x.Join("INNER", "food_problem_option", "food_problem_option.option_id = `option`.id").Where("food_problem_option.food_problem_id = ?", fp.Id).Find(&fp.OptionList)
		}
	}

	return diList, nil;
}













